package com.agile.leetcode.concurrent.threadlocal.daatsource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/26 14:09
 */
public class DataSourceUtils {
    /**
     * 定义threadLocal
     */
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    /**
     * 用户名
     */
    private static String username;
    /**
     * 密码
     */
    private static String password;
    /**
     * 数据库连接
     */
    private static String url;

    /**
     * 初始化连接
     */
    static {
        try {
            // 加载驱动
            Class.forName("com.jdbc.mysql.Driver");
            // 用户名
            username = "root";
            password = "1234";
            url = "jdbc:mysql://localhost:3306/test";
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取链接
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        // 先从threadLocal中拿
        Connection connection = threadLocal.get();
        // 是否为空
        if (connection == null) {
            // 获取
            connection = DriverManager.getConnection(url, username, password);
            // 添加到threadLocal中
            threadLocal.set(connection);
        }
        return connection;
    }

    /**
     * 释放连接
     */
    public void releaseConnection() {
        threadLocal.remove();
    }
}
